/**
 * 
 */
package santeclair.webext.util.jaxb;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.DataBindingException;
import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import santeclair.webext.bean.sso.ProfessionnelSanteSsoBean;
import santeclair.webext.bean.sso.SsoFflResponseBean;

/**
 * @author cquintin
 * 
 */
public class XmlGenerator {
    private static final Logger LOGGER = LoggerFactory.getLogger(XmlGenerator.class);

    private static final XmlGenerator INSTANCE = new XmlGenerator();

    private XmlGenerator() {

    }

    /**
     * 
     * @return
     */
    public static XmlGenerator getInstance() {
        return INSTANCE;
    }

    /**
     * 
     * @param ssoClass
     * @param datametier
     * @return
     */
    public ProfessionnelSanteSsoBean unmarshal(Class<? extends ProfessionnelSanteSsoBean> ssoClass, String datametier) {
        try {
            return JAXB.unmarshal(new StringReader(datametier), ssoClass);
            //
            //
            // Unmarshaller unmarshaller = JAXBContext.newInstance(ssoClass).createUnmarshaller();
            // unmarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
            // unmarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            //
            // StringReader reader = new StringReader(datametier);
            //
            //
            // StringWriter stringResult = new StringWriter();
            // unmarshaller.unmarshal (datametier);
            // return stringResult.toString();
        } catch (DataBindingException e) {
            LOGGER.warn(ExceptionUtils.getStackTrace(e));
            throw new IllegalArgumentException("Erreur lors de la construction du jeton " + e.getMessage(), e);
        }
    }

    /**
     * 
     * @param bean
     * @return String
     */
    public String marshal(SsoFflResponseBean bean) {
        try {
            Marshaller marshaller = JAXBContext.newInstance(SsoFflResponseBean.class).createMarshaller();
            StringWriter stringResult = new StringWriter();
            marshaller.marshal(bean, stringResult);
            return stringResult.toString();
        } catch (JAXBException e) {
            LOGGER.warn(ExceptionUtils.getStackTrace(e));
            throw new IllegalArgumentException("Erreur lors de la deserialization du jeton " + e.getMessage(), e);
        }

    }

}
